import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreSiteService extends BaseService<any> {
  private readonly logger = new Logger(CoreSiteService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getSiteCache
   * 对应 PHP: CoreSiteService_core::getSiteCache()
   * 逻辑类型: undefined - undefined
   */
  async getSiteCache(site_id: any) {
    // 基于PHP真实逻辑: getSiteCache
    // PHP原文: $cache_name = 'site_info_cache';         return cache_remember(             $cache_name . $site_id,             function() use ($site_id) {           ...
const cache_name = 'site_info_cache';
        return cache_remember(
            cache_name . site_id,
            function() use (site_id) {
                const where = [
                    [ 'site_id', '=', site_id ],
                ];
                const info = this.model.where(where).field('site_id, site_name, front_end_name, front_end_logo,front_end_icon, app_type, keywords, logo, icon, `desc`, status, latitude, longitude, province_id, city_id, district_id, address, full_address, phone, business_hours, create_time, expire_time, group_id, app, addons, site_domain, meta_title, meta_desc, meta_keyword').append([ 'status_name' )).findOrEmpty().toArray(];
                if (!!info)) {
                    const site_addons = ( this.coreSiteService ).getAddonKeysBySiteId((int) site_id];
                    info[ 'apps' ] = ( this.addonService ).where([ [ 'key', 'in', site_addons ], [ 'type', '=', AddonDict.APP ) )).field('key,title,desc,icon,type,support_app').select().toArray(];
                    info[ 'site_addons' ) = ( this.addonService ).where([ [ 'key', 'in', site_addons ], [ 'type', '=', AddonDict.ADDON ) )).field('key,title,desc,icon,type,support_app').select().toArray(];
                }
                return info;
  }

  /**
   * getSiteIdByDomain
   * 对应 PHP: CoreSiteService_core::getSiteIdByDomain()
   * 逻辑类型: undefined - undefined
   */
  async getSiteIdByDomain(domain: string) {
    // 基于PHP真实逻辑: getSiteIdByDomain
    // PHP原文: if (empty($domain)) return;          $cache_name = 'site_domain';         return cache_remember(             $cache_name . $domain,             functi...
if (!domain)) return;

        const cache_name = 'site_domain';
        return cache_remember(
            cache_name . domain,
            function() use (domain) {
                return this.model.where([ [ 'site_domain', '=', domain ) )).value('site_id');
  }

  /**
   * findRecord (原方法名: find)
   * 对应 PHP: CoreSiteService_core::find()
   * 逻辑类型: undefined - undefined
   * 注意: 为避免与BaseService方法冲突，已重命名
   */
  async findRecord(site_id: any) {
    // 基于PHP真实逻辑: find
    // PHP原文: return $this->model->findOrEmpty($site_id);     }      /**      * 获取过期的站点      * @return array      * @throws DataNotFoundException      * @throws DbE...
return this.model.findOrEmpty(site_id);
    }

    /**
     * 获取过期的站点
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getExpireSiteList()
    {
        return this.model.where([
            [ 'status', '<>', SiteDict.EXPIRE ),
            [ 'expire_time', 'between', [ 1, time() ] ],
        ]).field('site_id,status,site_name').select().toArray(];
    }

    /**
     * 站点到期(计划任务专用,切勿调用)
     * @param int site_id
     * @return bool
     */
    async expire(int site_id)
    {
        const site = this.find(site_id);
        if (site.isEmpty()) throw new BusinessException('SITE_NOT_EXIST');
        if (site.status == SiteDict.EXPIRE) throw new BusinessException('SITE_EXPIRE'];
        this.model.where([ [
            'site_id', '=', site_id
        ) )).update(
            [
                status: SiteDict.EXPIRE,
            )
        ];
        Cache.delete('site_info_cache' . site_id);
        Cache.tag(self.cache_tag_name . site_id).clear(];
        return true;
    }

    /**
     * 获取站点支持的应用插件
     * @param int site_id
     * @return */
    async getAddonKeysBySiteId(int site_id)
    {
        const cache_name = 'site_addon_key_cache';
        return cache_remember(
            cache_name . site_id,
            function() use (site_id) {
                const site_info = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).field('group_id,app_type,addons').findOrEmpty(];
                if (site_info.isEmpty()) return [];

                const app_type = site_info[ 'app_type' ];
                const group_addon_keys = [];

                if (app_type == AppTypeDict.SITE) {
                    const group_id = site_info[ 'group_id' ] || 0;
                    if (group_id > 0) {
                        const group = ( this.siteGroupService ).field('app,addon').findOrEmpty(group_id);
                        if (!group.isEmpty()) {
                            const group_addon_keys = Object.assign(group[ 'app' ), group[ 'addon' );
  }
                }
                //在查询站点所拥有的应用插件,两者结合
                const site_addon_keys = is_[site_info[ 'addons' )) ? site_info[ 'addons' ] : [];
                return array_unique(Object.assign(group_addon_keys || [), site_addon_keys)];
  }

  /**
   * getExpireSiteList
   * 对应 PHP: CoreSiteService_core::getExpireSiteList()
   * 逻辑类型: undefined - undefined
   */
  async getExpireSiteList() {
    // 基于PHP真实逻辑: getExpireSiteList
    // PHP原文: return $this->model->where([             [ 'status', '<>', SiteDict::EXPIRE ],             [ 'expire_time', 'between', [ 1, time() ] ],         ])->fi...
return this.model.where([
            [ 'status', '<>', SiteDict.EXPIRE ),
            [ 'expire_time', 'between', [ 1, time() ] ],
        ]).field('site_id,status,site_name').select().toArray(];
    }

    /**
     * 站点到期(计划任务专用,切勿调用)
     * @param int site_id
     * @return bool
     */
    async expire(int site_id)
    {
        const site = this.find(site_id);
        if (site.isEmpty()) throw new BusinessException('SITE_NOT_EXIST');
        if (site.status == SiteDict.EXPIRE) throw new BusinessException('SITE_EXPIRE'];
        this.model.where([ [
            'site_id', '=', site_id
        ) )).update(
            [
                status: SiteDict.EXPIRE,
            )
        ];
        Cache.delete('site_info_cache' . site_id);
        Cache.tag(self.cache_tag_name . site_id).clear(];
        return true;
    }

    /**
     * 获取站点支持的应用插件
     * @param int site_id
     * @return */
    async getAddonKeysBySiteId(int site_id)
    {
        const cache_name = 'site_addon_key_cache';
        return cache_remember(
            cache_name . site_id,
            function() use (site_id) {
                const site_info = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).field('group_id,app_type,addons').findOrEmpty(];
                if (site_info.isEmpty()) return [];

                const app_type = site_info[ 'app_type' ];
                const group_addon_keys = [];

                if (app_type == AppTypeDict.SITE) {
                    const group_id = site_info[ 'group_id' ] || 0;
                    if (group_id > 0) {
                        const group = ( this.siteGroupService ).field('app,addon').findOrEmpty(group_id);
                        if (!group.isEmpty()) {
                            const group_addon_keys = Object.assign(group[ 'app' ), group[ 'addon' );
  }
                }
                //在查询站点所拥有的应用插件,两者结合
                const site_addon_keys = is_[site_info[ 'addons' )) ? site_info[ 'addons' ] : [];
                return array_unique(Object.assign(group_addon_keys || [), site_addon_keys)];
  }

  /**
   * expire
   * 对应 PHP: CoreSiteService_core::expire()
   * 逻辑类型: undefined - undefined
   */
  async expire(site_id: number) {
    // 基于PHP真实逻辑: expire
    // PHP原文: $site = $this->find($site_id);         if ($site->isEmpty()) throw new CommonException('SITE_NOT_EXIST');         if ($site->status == SiteDict::EXPIR...
const site = this.find(site_id);
        if (site.isEmpty()) throw new BusinessException('SITE_NOT_EXIST');
        if (site.status == SiteDict.EXPIRE) throw new BusinessException('SITE_EXPIRE'];
        this.model.where([ [
            'site_id', '=', site_id
        ) )).update(
            [
                status: SiteDict.EXPIRE,
            )
        ];
        Cache.delete('site_info_cache' . site_id);
        Cache.tag(self.cache_tag_name . site_id).clear(];
        return true;
    }

    /**
     * 获取站点支持的应用插件
     * @param int site_id
     * @return */
    async getAddonKeysBySiteId(int site_id)
    {
        const cache_name = 'site_addon_key_cache';
        return cache_remember(
            cache_name . site_id,
            function() use (site_id) {
                const site_info = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).field('group_id,app_type,addons').findOrEmpty(];
                if (site_info.isEmpty()) return [];

                const app_type = site_info[ 'app_type' ];
                const group_addon_keys = [];

                if (app_type == AppTypeDict.SITE) {
                    const group_id = site_info[ 'group_id' ] || 0;
                    if (group_id > 0) {
                        const group = ( this.siteGroupService ).field('app,addon').findOrEmpty(group_id);
                        if (!group.isEmpty()) {
                            const group_addon_keys = Object.assign(group[ 'app' ), group[ 'addon' );
  }
                }
                //在查询站点所拥有的应用插件,两者结合
                const site_addon_keys = is_[site_info[ 'addons' )) ? site_info[ 'addons' ] : [];
                return array_unique(Object.assign(group_addon_keys || [), site_addon_keys)];
  }

  /**
   * getAddonKeysBySiteId
   * 对应 PHP: CoreSiteService_core::getAddonKeysBySiteId()
   * 逻辑类型: undefined - undefined
   */
  async getAddonKeysBySiteId(site_id: number) {
    // 基于PHP真实逻辑: getAddonKeysBySiteId
    // PHP原文: $cache_name = 'site_addon_key_cache';         return cache_remember(             $cache_name . $site_id,             function() use ($site_id) {      ...
const cache_name = 'site_addon_key_cache';
        return cache_remember(
            cache_name . site_id,
            function() use (site_id) {
                const site_info = ( this.siteService ).where([ [ 'site_id', '=', site_id ) )).field('group_id,app_type,addons').findOrEmpty(];
                if (site_info.isEmpty()) return [];

                const app_type = site_info[ 'app_type' ];
                const group_addon_keys = [];

                if (app_type == AppTypeDict.SITE) {
                    const group_id = site_info[ 'group_id' ] || 0;
                    if (group_id > 0) {
                        const group = ( this.siteGroupService ).field('app,addon').findOrEmpty(group_id);
                        if (!group.isEmpty()) {
                            const group_addon_keys = Object.assign(group[ 'app' ), group[ 'addon' );
  }
                }
                //在查询站点所拥有的应用插件,两者结合
                const site_addon_keys = is_[site_info[ 'addons' )) ? site_info[ 'addons' ] : [];
                return array_unique(Object.assign(group_addon_keys || [), site_addon_keys)];
  }

  /**
   * siteInitBySiteId
   * 对应 PHP: CoreSiteService_core::siteInitBySiteId()
   * 逻辑类型: undefined - undefined
   */
  async siteInitBySiteId(site_id: any, tables: any) {
    // 基于PHP真实逻辑: siteInitBySiteId
    // PHP原文: $prefix = config('database.connections.mysql.prefix');         if (!empty($prefix)){             foreach ($tables as &$value){                 $value ...
const prefix = config('database.connections.mysql.prefix');
        if (!!prefix)){
            foreach (tables as &value){
                const value = prefix.value;
            }
  }
}
